package com.jdj.framework.dao.mybatis.mapper.utils;

import com.jdj.framework.core.context.SpringContextUtil;
import com.jdj.framework.dao.mybatis.entity.BaseEntity;
import com.jdj.framework.dao.mybatis.mapper.BaseMapper;
import java.beans.Introspector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;

/**
 * Mapper工具类
 * @author caijinbang
 * @date 2019-04-14 13:10
 */
public class MapperUtils {
    protected final static Logger logger = LoggerFactory.getLogger(MapperUtils.class);

    /**
     * 根据实体，获取mapper实例，如果为空则抛出异常
     *
     * @param entity 实体
     * @return 实体
     */
    public static <Entity extends BaseEntity> BaseMapper getMapperInstanceByEntity(Entity entity) {
        return getMapperInstanceByMapperClass(entity.obtainEntityMapperClass());
    }

    /**
     * 根据实体class，获取mapper实例，如果为空则抛出异常
     *
     * @param entityClass 实体class
     * @return 实体mapper
     */
    public static <Entity extends BaseEntity> BaseMapper getMapperInstanceByEntityClass(Class<Entity> entityClass) {
        try {
            return getMapperInstanceByMapperClass(entityClass.newInstance().obtainEntityMapperClass());
        } catch (InstantiationException | IllegalAccessException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 根据 Mapper Class 获取 Spring 实例
     *
     * @param mapperClass 实体class
     * @return 实体mapper
     */
    private static BaseMapper getMapperInstanceByMapperClass(Class<?> mapperClass) {
        //实体名称
        String mapperName = ClassUtils.getShortName(mapperClass);
        //mapper id
        String mapperInstanceId = Introspector.decapitalize(mapperName);
        //获取Spring 实例
        BaseMapper mapperInstance = (BaseMapper) SpringContextUtil.getBean(mapperInstanceId);
        //
        if (mapperInstance == null) {
            throw new NullPointerException(mapperInstanceId + " (mapper) spring instance is null!");
        }
        return mapperInstance;
    }
}
